<template>
  <div class="contents">
    <el-table
      ref="table"
      :data="tableData"
      v-loading="loading"
      border
      style="width: 100%; margin-top: 10px"
      max-height="450"
      @select="handleSelectionChange"
      @select-all="handleSelectionAll"
    >
      <!-- @expand-change="expandChange"
      :expand-row-keys="expands"
      :row-key="getRowKeys" -->
      <el-table-column width="50" type="selection" reserve-selection>
        <!-- <template slot="header" slot-scope="scope">
          <el-checkbox
            :indeterminate="isIndeterminate"
            @change="handleSelectionChange"
            v-model="checkAll"
          ></el-checkbox>
        </template>

        <template slot-scope="scope">
          <el-checkbox
            v-model="scope.row.check"
            @change="singleChange(scope.row, scope.$index, $event)"
          ></el-checkbox>
        </template> -->
      </el-table-column>
      <el-table-column type="expand" width="50">
        <template slot-scope="props">
          <el-table
            :ref="'tableChild' + props.$index"
            :data="props.row.spu_list"
            border
            style="width: 95%; margin: auto"
            @select="handleSelectionChange2"
            @select-all="handleSelectionAll2"
          >
            <el-table-column type="selection" width="100" reserve-selection>
              <!-- <template slot="header" slot-scope="scope">
                <el-checkbox
                  :indeterminate="scope.row.isIndeterminate"
                  @change="handleSelectionChange"
                  v-model="scope.row.checkAll"
                ></el-checkbox>
                {{ scope.row }}
              </template>

              <template slot-scope="scope">
                <el-checkbox
                  v-model="scope.row.check"
                  @change="changErCheck(props.row, $event)"
                ></el-checkbox>
              </template> -->
            </el-table-column>
            <el-table-column label="规格名称" width="100">
              <template slot-scope="scope">{{
                scope.row.spu_name.title
              }}</template>
            </el-table-column>
            <el-table-column label="规格单位" width="100">
              <template slot-scope="scope">{{
                scope.row.spu_unit.title
              }}</template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template slot-scope="scope">
                <!-- {{ scope.row.number }} -->
                <!-- @blur="
                    checkNumber(
                      scope.row,
                      $event,
                      `${scope.row.id}${scope.$index}`
                    )" -->
                <el-input
                  :ref="`${scope.row.id}${scope.$index}`"
                  v-model="scope.row.number"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="起订量" width="80" prop="qiding">
            </el-table-column>
            <el-table-column label="现有库存" width="80"> </el-table-column>
            <el-table-column label="指定库存" width="80"> </el-table-column>
            <el-table-column label="描述" width="150" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="备注"> </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" width="180">
      </el-table-column>
      <el-table-column label="商品分类"></el-table-column>
    </el-table>

    <el-pagination
      style="text-align: right; margin-top: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageTotal.page"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageTotal.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  props: {
    loadings: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    // 监听加载状态
    loadings: {
      handler(value) {
        this.loading = value;
      },
      immediate: true,
    },
    list: {
      handler(value) {
        this.tableData = value;
        // 获取当前列表长度
        let totalCount = this.tableData.length;
        // 定义当前列表中激活状态的数量
        let someStatusCount = 0;
        this.tableData.forEach((item) => {
          if (item.check === true) {
            someStatusCount++;
          }
        });
        // 判断当前列表的总长度与激活状态的数量是否一致,一致则激活,反之则关闭
        this.checkAll = totalCount === someStatusCount ? true : false;
        // 判断多选框是否处于中立状态
        this.isIndeterminate =
          someStatusCount > 0 && someStatusCount < totalCount;
        if (this.checkAll && !this.isIndeterminate)
          this.isIndeterminateDisabled = true;
        else this.isIndeterminateDisabled = false;
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      // 表格的加载
      loading: false,
      tableData: [],

      pageTotal: {
        // 页码
        page: 1,
        // 页数
        pageSize: 20,
      },
      // 总数
      total: 0,

      // 通过这个字段判断，全选是选中，还是半选中，或者是未选中
      isIndeterminate: false,
      // 通过这个字段判断，全选操作是否允许点击
      isIndeterminateDisabled: false,
      checkAll: false,

      // 展开的表格列表,一次只展开一行
      expands: [],
      // getRowKeys(row) {
      //   return row.id;
      // },
    };
  },
  created() {},
  methods: {
    // 页数切换
    handleSizeChange() {},
    // 页码切换
    handleCurrentChange() {},
    // 点击全选功能
    handleSelectionChange() {},
    // 选择商品规格
    speChange(list, e) {
      console.log(list, e);
    },
    // 单个商品选中
    singleChange(row, index, e) {
      // 请用户先选择规格后方能追加至父组件的list中
      // if (!row.spu_id) {
      //   this.$message.error("请先选择规格!");
      //   row.check = false;
      //   return;
      // }
      // 通知父组件，单选了某个商品；当check激活时向父组件中追加数据，取消时向父组件中剔除数据
      let data = {
        list: row,
        state: null,
      };
      data.state = row.check ? "push" : "splice";
      this.$emit("addShopData", data);
    },

    // 对某一行展开或者关闭的时候会触发该事件
    expandChange(row, expandedRows) {
      console.log(row, expandedRows);
      let that = this;
      // 这里默认接收两个参数,row时当前行数据,  expandedRows是已经展开的行(数组)
      //只展开一行
      if (expandedRows.length) {
        //  说明展开了,  如果展开了多行,  这个数组会存放多个行id
        //  我们不需要多余的展开,  因此清空他,  给他push一个当前行的id即可
        that.expands = [];
        if (row) {
          that.expands.push(row.id); //只展开当前行id
        }
      } else {
        //说明收起了
        that.expands = [];
      }
    },
    // 对填写的数量进行校验
    checkNumber(row, $event, key) {
      // 获取填写的数量
      let numbers = $event.target.value;
      // 对比填写数量与起订量对比，如果低于起订量，则将起订量赋值给
      if (numbers < row.qiding) {
        this.$message.error("小于起订量");
        this.$refs[key].focus();
        return;
      }
    },

    // 修改二级复选框
    changErCheck(row, $event) {
      // console.log(row, $event);
      this.loading = true;
      let that = this;
      // 获取二级表格的数据
      let erTable = row.spu_list;
      // 过滤选中状态的数据，当返回的数据为空时，一级表格的复选框需修改为全选状态；否则修改为选中状态
      let data = erTable.filter((item) => !item.check);
      console.log(data);
      if (data.length == 0) {
        // row.isIndeterminate = true;
        // this.tableData[0].isIndeterminate = true
        that.$set(this.tableData[0], "isIndeterminate", true);
      }
      this.$nextTick(() => {
        console.log(this.tableData);
        this.loading = false;
      });
    },


    //一级表格勾选
    handleSelectionChange(selection, row) {
      console.log(selection, row, "一级表格勾选");
      //判断一级表格是否选中  选中--true  未选中--0
      let isCheck = selection.length && selection.indexOf(row) !== -1;
      //循环整个表数据--找到勾选的 index
      this.tableData.forEach((item, index) => {
        if (item.key == row.key) {
          //在勾选时展开本行数据--不然找不到toggleRowSelection
          this.$refs.table.toggleRowExpansion(item, true);
          let tempList = row.spu_list;
          this.$nextTick(() => {
            //以防二级列表没有数据
            if (tempList) {
              //循环本次勾选的数据
              tempList.forEach((selectionItem) => {
                this.$refs[`tableChild${index}`].toggleRowSelection(
                  selectionItem,
                  isCheck
                );
              });
            }
          });
        }
      });
    },
    //二级表格勾选
    handleSelectionChange2(selection, row) {
      console.log(selection, row);
      //判断二级列表是否取消勾选（无数据）
      let isCheck = selection.length > 0;
      this.tableData.forEach((item, index) => {
        if (item.key == row.key) {
          this.$refs.table.toggleRowSelection(item, isCheck);
        }
      });
    },

    //一级表格全选->子表格全部勾选
    handleSelectionAll(selection, row) {
      console.log(selection, row);
      this.tableData.forEach(async (item, index) => {
        await this.$refs.table.toggleRowExpansion(item, true);
        //判断取消还是勾选--取消清空选择数据
        if (selection) {
          this.$refs[`tableChild${index}`].toggleAllSelection();
        } else {
          this.$refs[`tableChild${index}`].clearSelection();
        }
      });
    },
    //子表格勾选 --->联动一级表格
    handleSelectionAll2(selection, row) {
      console.log(selection, row);
      if (selection.length > 0) {
        let list = this.tableData.find((item) => {
          return item.key === selection[0].key;
        });
        this.$refs.table.toggleRowSelection(list, true);
      } else {
        this.$refs.table.clearSelection();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.contents {
  width: 100%;
  .shopName {
    display: flex;
    flex-direction: column;
  }
}
</style>